﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using PocketMahjong.Core;

namespace PocketMahjong
{
	public partial class LayoutView : UserControl
	{
		public LayoutView()
		{
			InitializeComponent();
		}

		private Board _board;
		private Layout _layout;
		public Layout Layout
		{
			get { return _layout; }
			set 
			{ 
				_layout = value;
				if (value != null)
					_board = new Board(_layout, new RandomArrange());
				else
					_board = null;
				Invalidate();
			}
		}

		Brush TileBrush = new SolidBrush(Color.White);
		Pen TilePen = new Pen(Color.Blue, 1);
		protected override void OnPaint(PaintEventArgs e)
		{
			e.Graphics.Clear(Color.White);
			if (_board != null)
			{
				int CellWidth = 8;
				int CellHeight = 16;
				int sx = (int)((Width - Math.Ceiling(_board.ColumnCount / 2.0) * CellWidth) / 2);
				int sy = (int)((Height - Math.Ceiling(_board.RowCount / 2.0) * CellHeight) / 2);

				for (int lay = 0; lay < _board.LayerCount; lay++)
				{
					for (int col = _board.ColumnCount; col >= 0; col--)
					{
						for (int row = 0; row < _board.RowCount; row++)
						{
							var pos = new Position(lay, row, col);
							var tile = _board[lay, row, col];
							if (tile != null)
							{
								int x = sx + pos.Column * CellWidth / 2 + pos.Layer * 2;
								int y = sy + pos.Row * CellHeight / 2 - pos.Layer * 2;
								var rect = new Rectangle(x, y, CellWidth, CellHeight);
								e.Graphics.FillRectangle(TileBrush, rect);
								e.Graphics.DrawRectangle(TilePen, rect);
							}
						}
					}
				}
			}
		}

		protected override void OnPaintBackground(PaintEventArgs e)
		{
		}
	}
}
